<?php


namespace app\actions;


use app\models\Book;
use Yii;
use yii\base\Action;
use yii\helpers\Url;
use yii\web\Response;

class SiteMapAction extends Action {

    public function run() {
        $items = Book::find()->select('id, title, create_time, update_time, view_count')->asArray()->orderBy('view_count desc')->all();

        $response = Yii::$app->response;
        $response->format = Response::FORMAT_RAW;
        $response->headers->add('Content-Type', 'text/xml');

        $baseUrl = Url::to('/', TRUE);

        $p = 1000;
        $xml_data = [];
        foreach ($items as $i => $item) {
            $i += 1;
            $index = intval($i / $p);
            $t = $item['update_time'] ? $item['update_time'] : $item['create_time'];
            $date = date('Y-m-d\TH:i:s\Z', $t);
            $url = Url::to(['comic/detail', 'id' => $item['id']]);
            $xml_data[$index][] = $this->buildXml($url, $date);
        }

        $date = date('Y-m-d\TH:i:s\Z');
        $xml_home_file = PUBLIC_ROOT . '/sitemap-home.xml';
        $this->generatorXml($this->buildXml($baseUrl, $date, 1.0), $xml_home_file);
        $xml_map = [$this->buildXmlMap("{$baseUrl}sitemap-home.xml", $date)];
        foreach ($xml_data as $i => $data) {
            $i += 1;
            $file = PUBLIC_ROOT . "/sitemap-{$i}.xml";
            $this->generatorXml($data, $file);
            $xml_map[] = $this->buildXmlMap("{$baseUrl}sitemap-{$i}.xml", $date);
        }
        return $this->generatorXmlMap($xml_map, PUBLIC_ROOT . '/sitemap.xml');
    }

    protected function buildXmlMap($url, $date) {
        $xml = [
            "\t<sitemap>",
            "\t\t<loc>{$url}</loc>",
            "\t\t<lastmod>{$date}</lastmod>",
            "\t</sitemap>"
        ];
        return join("\n", $xml);
    }

    protected function generatorXmlMap($data, $file) {
        $xsl = Url::to('/assets/sitemap/xsl/index.xsl', TRUE);
        $xml_map = ['<?xml version="1.0" encoding="UTF-8"?>'];
        $xml_map[] = "<?xml-stylesheet type=\"text/xsl\" href=\"{$xsl}\"?>";
        $xml_map[] = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
		http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd">';
        $xml_map = array_merge($xml_map, $data);
        $xml_map[] = "</sitemapindex>";
        $xml_string = join("\n", $xml_map);
        file_put_contents($file, $xml_string);
        return $xml_string;
    }

    protected function generatorXml($data, $file) {
        $xsl = Url::to('/assets/sitemap/xsl/data.xsl', TRUE);
        $xml = ['<?xml version="1.0" encoding="UTF-8"?>'];
        $xml[] = "<?xml-stylesheet type=\"text/xsl\" href=\"{$xsl}\"?>";
        $xml[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
		http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
        if (is_string($data)) {
            $xml[] = $data;
        } else {
            $xml = array_merge($xml, $data);
        }
        $xml[] = "</urlset>";
        $xml_string = join("\n", $xml);
        file_put_contents($file, $xml_string);
        return $xml_string;
    }

    protected function buildXml($url, $date, $priority = 0.8) {
        $xml = [
            "\t<url>",
            "\t\t<loc>{$url}</loc>",
            "\t\t<priority>{$priority}</priority>",
            "\t\t<changefreq>daily</changefreq>",
            "\t\t<lastmod>{$date}</lastmod>",
            "\t</url>"
        ];
        return join("\n", $xml);
    }
}